package com.example.bookmanage.service;

import com.example.bookmanage.dao.BookDao;
import com.example.bookmanage.pojo.Book;
import com.example.bookmanage.service.ex.insertException;
import com.example.bookmanage.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BookServiceImpl implements  BookService{
    //这里引用到了dao中的mapper
    private BookDao mapper;
    @Autowired
    public void setMapper(BookDao mapper) {
        this.mapper = mapper;
    }
    @Override
    public JsonResult<Book> findData(int page,int limit,String time1,String time2) {
        JsonResult<Book> jsonResult=new JsonResult<Book>();
        jsonResult.setCode(0);
        jsonResult.setMsg("");
        jsonResult.setCount(mapper.CountBookByTime(time1,time2));//按照条件查询的数据总数
        jsonResult.setData(mapper.queryAllBookByTime(page,limit,time1,time2));
        return jsonResult;
    }
    @Override
    public void insertBook(Book book) {
        //先根据传过来的数据查找是否已经存在了该本书
        String bookName = book.getBookName();
        List<Book> books = mapper.queryBookByName(bookName);
        //new 一个 结果类 并将他的范型区域设置为空
       //这里涉及一个集合判空操作
        if (books.size()!=0){
            //不为空表示已经有该本书了
            //设置返回值得code并将异常抛出
            throw new insertException("该用本已经被注册了");
        }else {
            boolean br = mapper.insertBook(book);
            if(!br){
                throw new insertException("注册失败,产生了未知错误");
            }
        }
        //是否存在插入异常
    }
    @Override
    public void delete(Integer id) {
        mapper.delete(id);
    }

    @Override
    public int CountAllBook() {
        return mapper.CountAllBook();
    }

    @Override
    public JsonResult<Book> queryBookByName(String bookName) {
        JsonResult<Book> jsonResult=new JsonResult<Book>();
        jsonResult.setCode(0);
        jsonResult.setMsg("");
        jsonResult.setData(mapper.queryBookByName(bookName));
        jsonResult.setCount(1);
        return jsonResult;
    }

    @Override
    public int CountBookByTime(String time1, String time2) {
        //这里返回的是一个整数
        return mapper.CountBookByTime(time1,time2);
    }

    @Override
    public boolean updateBook(Book book) {
       return mapper.updateBook(book);
    }
}
